package net.cyue.util;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;


public class JWTUtil {

    public static SecretKey generateKey(String password) {
        if (password.length() > 256) {
            password = password.substring(0, 256);
        }

        byte[] bs = new byte[256];
        byte[] passwordBytes = password.getBytes();
        Arrays.fill(bs, (byte) 0);
        System.arraycopy(passwordBytes, 0, bs, 0, passwordBytes.length);
        return Keys.hmacShaKeyFor(bs);
    }

    public static String generateJWT(String password, Map<String, ?> claims) {
        return JWTUtil.generateJWT(password, claims, null);
    }
    public static String generateJWT(String password, Map<String, ?> claims, Date expiration) {
        JwtBuilder builder = Jwts.builder();
        builder.claims(claims);
        if (expiration != null) {
            builder.expiration(expiration);
        }
        SecretKey key = JWTUtil.generateKey(password);
        return builder.signWith(key).compact();
    }

    public static boolean verify(String jwt, String password) {
        SecretKey key = JWTUtil.generateKey(password);
        try {
            Jwts
                .parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(jwt);
            return true;
        } catch (JwtException e) {
            return false;
        }
    }
}

